package com.fast.exception;

import com.fast.model.result.common.R;
import com.fast.model.result.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalException {
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public R MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        // 从异常对象中拿到ObjectError对象
        FieldError fieldError = e.getBindingResult().getFieldError();
        return new R<>(ResultCode.VALIDATE_ERROR, fieldError.getField()+":"+fieldError.getDefaultMessage());
    }

    @ExceptionHandler(ServiceException.class)
    public R ServiceExceptionHandler(ServiceException e) {
        log.error(e.getMessage(), e);
        return new R<>(e.getCode(), e.getMsg(), e.getMessage());
    }

    @ExceptionHandler({Exception.class})
    public R validationExceptionExceptionHandler(Exception e) {
        return new R<>(ResultCode.VALIDATE_ERROR, e.getMessage());
    }


}
